#include "buffered_reader.h"
#ifdef _WIN32
#   include <winsock2.h>
#else
#   include <sys/socket.h>
#endif
#include <iostream>
using std::cout;
using std::endl;

BufferedReader::BufferedReader(int sock)
    :m_sock(sock), m_charCountInBuffer(0), m_indexInBuffer(0)
{
    // ctor
}

BufferedReader::~BufferedReader()
{
    // dtor
}

bool BufferedReader::getChar(char& chr)
{
    bool result = false;
    if (m_charCountInBuffer == m_indexInBuffer) {
        // buffer used up, fill data into buffer
        m_charCountInBuffer = recv(m_sock, m_buffer, sizeof(m_buffer), 0);
        m_indexInBuffer = 0;
    }
    if (m_indexInBuffer < m_charCountInBuffer) {
        chr = m_buffer[m_indexInBuffer++];
        result = true;
    }
    return result;
}

bool BufferedReader::getLine(string& str)
{
    bool result = false;

    str.clear();
    while (true) {
        char chr;
        result = getChar(chr);
        if (!result || chr == '\n') {
            break;
        }
        str += chr;
    }
    return !str.empty();
}

